#import "SpotifyPlugin_tPlugin.h"

static NSObject *obj = NULL;
@implementation SpotifyPlugin_tPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"spotify_plugin_t"
            binaryMessenger:[registrar messenger]];
  SpotifyPlugin_tPlugin* instance = [[SpotifyPlugin_tPlugin alloc] init];
    
    FlutterEventChannel * event = [FlutterEventChannel eventChannelWithName:@"spotify_plugin_t_eventChannel" binaryMessenger:registrar.messenger];
    [event setStreamHandler:instance];
    
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events{
    self.sink = events;
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments{
    return nil;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"getSpotifyCode" isEqualToString:call.method]) {
      
      NSDictionary *dic = @{
          @"playlistReadPrivate":@(SPTPlaylistReadPrivateScope),
          @"playlistReadCollaborative":@(SPTPlaylistReadCollaborativeScope),
          @"playlistModifyPublic":@(SPTPlaylistModifyPublicScope),
          @"playlistModifyPrivate":@(SPTPlaylistModifyPrivateScope),
          @"userFollowRead":@(SPTUserFollowReadScope),
          @"userFollowModify":@(SPTUserFollowModifyScope),
          @"userLibraryRead":@(SPTUserLibraryReadScope),
          @"userLibraryModify":@(SPTUserLibraryModifyScope),
          @"userReadBirthDate":@(SPTUserReadBirthDateScope),
          @"userReadEmail":@(SPTUserReadEmailScope),
          @"userReadPrivate":@(SPTUserReadPrivateScope),
          @"userTopRead":@(SPTUserTopReadScope),
          @"ugcImageUpload":@(SPTUGCImageUploadScope),
          @"streaming":@(SPTStreamingScope),
          @"appRemoteControl":@(SPTAppRemoteControlScope),
          @"userReadPlaybackState":@(SPTUserReadPlaybackStateScope),
          @"userModifyPlaybackState":@(SPTUserModifyPlaybackStateScope),
          @"userReadCurrentlyPlaying":@(SPTUserReadCurrentlyPlayingScope),
          @"userReadRecentlyPlayed":@(SPTUserReadRecentlyPlayedScope)
      };
      
      NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
      NSArray *keys = [dic allKeys];
      for (int i=0; i<keys.count; i++) {
          NSString *key = keys[i];
          muDic[[key lowercaseString]] = dic[key];
      }
      self.dicObj = muDic;
      
      NSString * clientID = call.arguments[@"clientId"];
      NSString * urlStr = call.arguments[@"url"];
      NSString * scopestr = call.arguments[@"scope"];
      scopestr = [scopestr stringByReplacingOccurrencesOfString:@"-" withString:@""];
      NSArray * scopeArr = [scopestr componentsSeparatedByString:@","];
      SPTConfiguration *configuration = [SPTConfiguration configurationWithClientID:clientID
                                                                        redirectURL:[NSURL URLWithString:urlStr]];
    
      self.sessionManager = [SPTSessionManager sessionManagerWithConfiguration:configuration
                                                                      delegate:self];
    
      
      NSInteger scope = -999;
      for (int i=0; i< scopeArr.count; i++) {
          NSInteger tmp = [self getScopeByName:scopeArr[i]];
          if (tmp != -999) {
              if (scope == -999) {
                  scope = tmp;
              } else {
                  scope = scope | tmp;
              }
          }
      }
      //[self.sessionManager initiateSessionWithScope:scope options:SPTClientAuthorizationOption];
      [self.sessionManager initiateSessionWithScope:scope options:SPTClientAuthorizationOption campaign:nil];
      
  } else if ([@"getTokenByCode" isEqualToString:call.method]) {
      self.resultBlock = result;
      NSString * url = call.arguments[@"url"];
      [self.sessionManager application:NULL openURL:[NSURL URLWithString:url] options:NULL];
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}

- (NSInteger) getScopeByName:(NSString *)name{
    
    if ([[self.dicObj allKeys] containsObject:name]){
        return [self.dicObj[name] intValue];
    }
    return -999;
}

#pragma mark - SPTSessionManagerDelegate

- (void)sessionManager:(SPTSessionManager *)manager didInitiateSession:(SPTSession *)session
{
    NSDictionary *dic = @{
        @"type":@"token",
        @"accessToken":session.accessToken,
        @"refreshToken":session.refreshToken
    };
    self.sink(dic);
}

- (void)sessionManager:(SPTSessionManager *)manager didFailWithError:(NSError *)error
{
//    NSDictionary *dic = @{
//        @"type":@"token",
//        @"accessToken":@"",
//        @"refreshToken":@"",
//        @"error": error.description
//    };
//    self.sink(dic);
}

- (void)sessionManager:(SPTSessionManager *)manager didRenewSession:(SPTSession *)session
{
    NSDictionary *dic = @{
        @"type":@"token",
        @"accessToken":session.accessToken,
        @"refreshToken":session.refreshToken
    };
    self.sink(dic);
}

- (BOOL)sessionManager:(SPTSessionManager *)manager shouldRequestAccessTokenWithAuthorizationCode:(SPTAuthorizationCode)code NS_SWIFT_NAME(sessionManager(manager:shouldRequestAccessTokenWith:)){
    return YES;
}

@end

